package com.eascs.web.o2o.web.reward.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.IoUtil;
import com.eascs.common.util.UrlUtil;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.PaginationRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.web.context.RequestContext;
import com.eascs.web.o2o.web.reward.entity.RiskAmountQueryForm;
import com.eascs.web.o2o.web.reward.service.RiskAmountService;
import com.eascs.web.o2o.web.util.ExcelParser;
import com.eascs.web.o2o.web.util.ExcelType;

/**
 * tick:report-10348 风险金计提报表查询, 导入, 导出功能
 * @author:hzp
 * @date:2018年4月2日
*/
@RestController
@RequestMapping("/riskRest")
public class RiskAmountRestController extends BaseRestController{

	private static Logger log = LoggerFactory.getLogger(ProvinceRewardRestController.class);

	@Autowired
	RiskAmountService ras;
	
  	
  	@RequestMapping("/query")
  	public PaginationRestResult rewardReportDetail(RiskAmountQueryForm entity) {
  		String o2ourl = "/provinceRewardRest/query";
  		Calendar c = Calendar.getInstance();
		c.add(Calendar.MONTH, -1);
		String date=new SimpleDateFormat("yyyy-MM").format(c.getTime());
		String month = entity.getMonth()==null?date:entity.getMonth();
		entity.setMonth(month);
		String province = entity.getProvince() == null ? "" : entity.getProvince();
		String monthData = entity.getMonth() == null ? "" : entity.getMonth();
		o2ourl = UrlUtil.appendUrl(o2ourl, "month", monthData);
		o2ourl = UrlUtil.appendUrl(o2ourl, "province", province);
		o2ourl = o2ourl + "&showPage=";
  		
		entity.setPageSize(15);
  		PageResult<Object[]> pageResult = ras.getRiskAmount(entity);
  		String titles[] = { "考核月份", "省区code", "计提人工号", "计提人姓名", "贷款单号", "借款人姓名", "信贷经理姓名", "放款金额（万元）", "放款日期", "到期日期", "业绩提成系数", "计提比例", "计提金额（万元）", "被考核对象与本单的关系"};
  		SelectDataOption[] selectDataOptions = { null, null,null, null, null, null, null,null, null,null, null, null, null, null};
  		PaginationInfo o2oPagingInfo = new PaginationInfo(pageResult, titles, UrlUtil.resetParam(RequestContext.getRequestUrlWithQueryString(), "showPage", ""));

  		o2oPagingInfo.setBuildPagingNavigation(true);
  		o2oPagingInfo.setFirstRenderColumnIndex(0);
  		o2oPagingInfo.setSelectDataOptions(selectDataOptions);
  		o2oPagingInfo.setRendTo("#o2o_result");
  		ViewContext.put("vo", entity);
  		return PaginationRestResult.buildPaginationRestResult(o2oPagingInfo);
  	}
	
  	@RequestMapping("/toImport")
	public HtmlRestResult toImport(String type) {
  		ViewContext.put("type", type);
		return HtmlRestResult.popHtmlFragment("risk/import_risk_amount");
	}

	//数据导入
  	@RequestMapping("/uploadExecl")
	public BaseRestResult<String> uploadExcel(@RequestParam(value = "file", required = false) MultipartFile file, String downtype) {
		@SuppressWarnings("unused")
		InputStream inputStream = null;
		try {
			inputStream = file.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		//设置单元格的校验
		ExcelType[] types = setExcel(downtype);
		
		long beginTime = System.currentTimeMillis();
		ExcelParser parser = new ExcelParser(types);
		try {
			parser.run(file.getInputStream());
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		List<Object> errorresults = parser.getErrorresults();
		StringBuffer error = new StringBuffer();
		for (int i = 0; i < errorresults.size(); i++) { //如果数据格式有问题，先打出loger 
			error.append("导入数据有误请检查：错误数据位置为："+(String) errorresults.get(i)+"\r\n");
			log.error("error.excel.read:{}", (String) errorresults.get(i));
		}
		if(error!=null&&StringUtils.isNotBlank(error)){
			return BaseRestResult.warn(error.toString());
		}
		
		 //解析出来的数据
		List<List<Object>> results = parser.getResults(); 
		//循环去查询表插入省区绩效奖金报表
		log.info("耗时:{} , 导入记录数:{} , ,批量导入级别-导入Excel", System.currentTimeMillis() - beginTime , results.size());
		try {
			if("risk_amount".equals(downtype))
				ras.addRiskAmountList(results);
		} catch (RuntimeException e) {
			log.error("更新风险金计提报表出错", e);
			return BaseRestResult.info(e.getLocalizedMessage()).andRefresh();
		}
		return BaseRestResult.info("导入成功").andRefresh();
	}
  	
  	
  	private ExcelType[] setExcel(String type) {
		ExcelType[] types=null;
		if("risk_amount".equals(type)){
			types = new ExcelType[] {//验证excel数据是否正确
					new ExcelType(ExcelType.CELL_TYPE_STRING, true),//1考核月份
					new ExcelType(ExcelType.CELL_TYPE_STRING, false),//2省区code
					new ExcelType(ExcelType.CELL_TYPE_STRING, false),//3，省区
					new ExcelType(ExcelType.CELL_TYPE_STRING, false),//4，计提人no
					new ExcelType(ExcelType.CELL_TYPE_STRING, false),//5，计提人工号
					new ExcelType(ExcelType.CELL_TYPE_STRING, false),//6，计提人姓名
					new ExcelType(ExcelType.CELL_TYPE_STRING, true),//7贷款单号
					new ExcelType(ExcelType.CELL_TYPE_STRING, false),//8借款人姓名
					new ExcelType(ExcelType.CELL_TYPE_STRING, false),//9信贷经理工号
					new ExcelType(ExcelType.CELL_TYPE_STRING, false),//10信贷经理姓名
					new ExcelType(ExcelType.CELL_TYPE_STRING, false),//11，放款金额（万元）
					new ExcelType(ExcelType.CELL_TYPE_STRING, false),//12放款期限
					new ExcelType(ExcelType.CELL_TYPE_DATE, false),//13，放款日期
					new ExcelType(ExcelType.CELL_TYPE_DATE, false),//14到期日期
					new ExcelType(ExcelType.CELL_TYPE_STRING, false),//15业绩提成系数
					new ExcelType(ExcelType.CELL_TYPE_STRING, false),//16，计提比例
					new ExcelType(ExcelType.CELL_TYPE_STRING, false),//17，计提金额（万元）
					new ExcelType(ExcelType.CELL_TYPE_STRING, false),//18被考核对象与本单关系
					new ExcelType(ExcelType.CELL_TYPE_STRING, false),//19经营平台no
					new ExcelType(ExcelType.CELL_TYPE_STRING, false),//20经营平台code
					new ExcelType(ExcelType.CELL_TYPE_STRING, false),//21经营平台名称
			};
		}			
		return types;
	}
  	
    //模板导出
  	@RequestMapping("/download")
  	public BaseRestResult<String> dowanload(HttpServletResponse httpServletResponse, HttpServletRequest request,String type) {
  		BaseRestResult<String> result = null;
  		String file = "";
  		String outfile ="";
  		if((type).equals("risk_amount")){
  			 file = RiskAmountRestController.class.getResource("/excelTemplate/risk_amount_detail.xls").getPath();
  			 outfile = "风险金计提报表模板.xls";
  		}
  		OutputStream os = null;
  		try {
  			String userAgent = request.getHeader("User-Agent");
  			byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
  			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
  			File f = new File(file);
  			if (!f.exists())
  				throw new RuntimeIOException("file not found");
  			os = httpServletResponse.getOutputStream();
  			httpServletResponse.reset();
  			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
  			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
  			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  			IoUtil.fileToOutputStream(f, byteArrayOutputStream);
  			os.write(byteArrayOutputStream.toByteArray());
  			os.flush();
  		} catch (IOException e) {
  			throw new RuntimeIOException(e);
  		} finally {
  			IoUtil.close(os);
  		}
  		return result;
  	}  	
}
